<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkContact\Logic\FieldPivot;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\Codec\Json;
use MoChat\App\WorkContact\Contract\ContactFieldContract;
use MoChat\App\WorkContact\Contract\ContactFieldPivotContract;
use MoChat\App\WorkContact\Contract\WorkContactContract;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Plugin\ContactTrack\Constants\Event;
use MoChat\Plugin\ContactTrack\Constants\EventName;
use MoChat\Plugin\ContactTrack\Contract\ContactTrackContract;

/**
 * 修改用户画像-手机号.
 *
 * Class UpdatePhoneLogic
 */
class UpdatePhoneLogic
{
    /**
     * 客户表.
     * @Inject
     * @var WorkContactContract
     */
    protected $workContactService;

    /**
     * 画像表.
     * @Inject
     * @var ContactFieldContract
     */
    protected $contactFieldService;

    /**
     * 用户画像表.
     * @Inject
     * @var ContactFieldPivotContract
     */
    private $contactFieldPivotService;

    /**
     * 互动轨迹表.
     * @Inject
     * @var ContactTrackContract
     */
    private $contactTrackService;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * 参数.
     * @var array
     */
    private $params;

    /**
     * @return array
     */
    public function handle(array $params)
    {
        $this->params = $params;

        // 修改用户画像 并记录轨迹
        try {
            $this->update();
        } catch (\Throwable $e) {
            $this->logger->error(sprintf('[客户画像]客户手机号更新失败，错误信息: %s', $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
        }

        return [];
    }

    /**
     * 修改用户画像 并记录轨迹.
     */
    private function update(): array
    {
        if (empty($this->params['remarkMobiles']) || empty($this->params['contactId'])) {
            return [];
        }

        // 客户
        $contactId = (int) $this->params['contactId'];
        $contact = $this->workContactService->getWorkContactById($contactId, ['corp_id']);
        if (empty($contact)) {
            return [];
        }
        $corpId = $this->params['corpId'] = $contact['corpId'];

        // 用户画像-手机号
        $fieldPhone = $this->contactFieldService->getContactFieldByCorpIdName($corpId, 'phone', ['id']);
        if (empty($fieldPhone)) {
            return [];
        }

        $content = '编辑用户画像：';
        // 用户画像值-手机号
        $contactFieldPhone = $this->contactFieldPivotService->getContactFieldPivotsByOtherId($contactId, [$fieldPhone['id']], ['id', 'value']);
        // 如果没有用户画像 则新增
        if (empty($contactFieldPhone)) {
            // 新增用户画像
            $createData[] = [
                'contact_id' => $contactId,
                'contact_field_id' => $fieldPhone['id'],
                'value' => $this->params['remarkMobiles'][0],
            ];
            // 记录轨迹
            if (! empty($this->params['remarkMobiles'][0])) {
                // 轨迹数据
                $content .= '手机号 ';
            }
        } elseif ($this->params['remarkMobiles'][0] != $contactFieldPhone[0]['value']) {
            // 轨迹数据
            $content .= '手机号 ';
            $updateRes = $this->contactFieldPivotService
                ->updateContactFieldPivotById($contactFieldPhone[0]['id'], ['value' => $this->params['remarkMobiles'][0]]);
            if (! is_int($updateRes)) {
                throw new CommonException(ErrorCode::SERVER_ERROR, '编辑用户画像失败');
            }
        }

        if ($content != '编辑用户画像：') {
            // 记录轨迹
            $this->recordTrack($content);
        }

        if (! empty($createData)) {
            $createRes = $this->contactFieldPivotService->createContactFieldPivots($createData);
            if ($createRes != true) {
                throw new CommonException(ErrorCode::SERVER_ERROR, '添加用户画像失败');
            }
        }
        return [];
    }

    /**
     * 记录轨迹.
     * @param $content
     */
    private function recordTrack($content)
    {
        $jsonContact = [
            'title' => EventName::INFO,
            'content' => $content,
        ];
        $data = [
            'employee_id' => $this->params['employeeId'],
            'contact_id' => $this->params['contactId'],
            'content' => Json::encode($jsonContact),
            'corp_id' => $this->params['corpId'],
            'event' => Event::USER_PORTRAIT,
        ];

        $res = $this->contactTrackService->createContactTrack($data);
        if (! is_int($res)) {
            throw new CommonException(ErrorCode::SERVER_ERROR, '记录轨迹失败');
        }
    }
}
